<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>Canvas 控制 Lottie 动画移动</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.12.2/lottie.min.js"></script>
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }

    .canvas-container {
      width: 100vw;
      height: 100vh;
    }
  </style>
</head>

<body>
  <div id="lottieContainer">

  </div>

  <script>
    // 确保 DOM 加载完成
    document.addEventListener('DOMContentLoaded', function () {
      // 验证 Lottie 库是否加载成功
      if (typeof lottie === 'undefined') {
        console.error('Lottie 库加载失败！');
        return;
      }
      const container = document.getElementById('lottieContainer');

      // 加载 Lottie 动画
      const animation = lottie.loadAnimation({
        container: container,
        renderer: 'canvas',
        path: 'http://localhost:8000/lottie/Animation1750837500866.json',
        autoplay: true
      });

      // 添加动画播放完成监听，确保动画加载完成
      animation.addEventListener('DOMLoaded', function () {
        const canvas = container.querySelector('canvas');
        if (!canvas) return;
        const ctx = canvas.getContext('2d');
        const originalDraw = ctx.drawImage;

        const startTime = performance.now();
        const duration = 5000; // 动画时长 5 秒
        const startX = 0;
        const endX = window.innerWidth - canvas.width;

        function animate(currentTime) {
          const elapsed = currentTime - startTime;
          const progress = Math.min(elapsed / duration, 1);
          const currentX = startX + (endX - startX) * progress;
            
          // 重写 drawImage 方法实现平移
          ctx.drawImage = function (...args) {
            console.log(args)
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.save();
            ctx.translate(currentX, 0);
             originalDraw.apply(ctx, args);
            ctx.restore();
          };

          if (progress < 1) {
            requestAnimationFrame(animate);
          }

        }

        requestAnimationFrame(animate);
      });
    });
  </script>
</body>

</html>